<?php

namespace KukePay\Tencent\Payment\Oauth;

use KukePay\ExceptionHandler;
use KukePay\Tencent\Payment\Kernel\ConfigFactory;

/**
 * 微信公众号授权
 * @package KukePay\Tencent\Native
 */
class Factory extends \KukePay\Kernel\Factory
{
    private $config;
    private $scopes;

    /**
     * Factory constructor.
     * @param ConfigFactory $config
     */
    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        parent::__construct();
    }

    /**
     * 设置授权模式
     * @param $scopes
     * @return $this
     */
    public function setScopes($scopes)
    {
        $this->scopes = $scopes;
        return $this;
    }

    /**
     * 获取授权地址
     * @param string $redirect
     * @return string
     */
    public function redirect(string $redirect)
    {
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->config->getAppId().'&redirect_uri='.urlencode($redirect).'&response_type=code&scope='.$this->scopes.'&state=STATE#wechat_redirect';
    }

    /**
     * @param string $code
     * @return mixed|string
     */
    public function getUserInfo(string $code)
    {
        try{
            if (!isset($code)) throw new ExceptionHandler('can not be empty');

            if (!isset($this->scopes)) throw new ExceptionHandler('Please set up scopes))');

            $uri = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->config->getAppId().'&secret='.$this->config->getSecret().'&code='.$code.'&grant_type=authorization_code';

            $accessToken = $this->request->get($uri)->getBody()->getContents();

            $accessToken = json_decode($accessToken,true);

            if (!isset($accessToken['access_token']) || !isset($accessToken['openid'])) throw new ExceptionHandler($accessToken['errmsg']);

            if ($this->scopes == 'snsapi_base') return $accessToken;

            $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken['access_token']}&openid={$accessToken['openid']}&lang=zh_CN";

            $userInfo = $this->request->get($get_user_info_url)->getBody()->getContents();

            return json_decode($userInfo,true);

        }catch (ExceptionHandler $exception){
            return $exception->getMessage();
        }
    }

    private function getContKey()
    {
        return 'swoole_pay_oauth2_access_token';
    }

}